package com.quan.system.service.impl;

import java.io.Serializable;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quan.common.core.MyBaseServiceImpl;
import com.quan.system.entity.SystemMenu;
import com.quan.system.mapper.SystemMenuMapper;
import com.quan.system.service.SystemMenuService;
import com.quan.system.service.SystemPermissionService;
import com.quan.system.service.SystemRolePermissionService;

/**
 * <p>
 * 通用用户权限系统-菜单表 服务实现类
 * </p>
 *
 * @author 杨浩泉
 * @since 2019-06-03
 */
@Service
public class SystemMenuServiceImpl extends MyBaseServiceImpl<SystemMenuMapper, SystemMenu> implements SystemMenuService {
	
	@Autowired
	private SystemRolePermissionService rolePermissionService ;
	
	@Autowired
	private SystemPermissionService permissionService ;
	
	@Override
	public boolean removeById(Serializable id) {
		return this.recursiveDelete(id);
	}
	
	private boolean recursiveDelete(Serializable id) {
		QueryWrapper<SystemMenu> queryWrapper = new QueryWrapper<SystemMenu>();
		queryWrapper.eq("pid", id);
		
		List<SystemMenu> child = super.list(queryWrapper) ;
		if(null != child) {
			for (SystemMenu entity : child) {
				this.permissionService.deleteByMenuId(entity.getId());
				recursiveDelete(entity.getId());
			}
		}
		
		//删除与角色关联的数据
		this.rolePermissionService.deleteByMenuId(id);
		
		return super.removeById(id);
	}
	
	@Override
	public List<SystemMenu> listWithTree() {
		// 1、查出所有分类
		List<SystemMenu> entities = super.list();
		
		// 2、组装成父子的树形结构
		List<SystemMenu> rootLevel = entities.stream().filter((entity) -> {
			// 1、找到所有一级分类
			return entity.getPid() == 0;
		}).map((menu) -> {
			// 2、找到所有子菜单
			return menu.setChildren(getChildren(menu, entities));
		}).sorted((menu1, menu2) -> {
			// 3、排序
			return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
		}).collect(Collectors.toList());
		
		
		return rootLevel;
	}
	
	/**
	 * 递归查找所有菜单的子菜单
	 * @param root
	 * @param all
	 * @return
	 */
	public List<SystemMenu> getChildren(SystemMenu root, List<SystemMenu> all) {
		List<SystemMenu> children = all.stream().filter((entity) -> {
			return entity.getPid() == root.getId();
		}).map((entity) -> {
			// 1、递归找到子菜单
			return entity.setChildren(getChildren(entity, all));
		}).sorted((menu1, menu2) -> {
			// 2、排序
			return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
		}).collect(Collectors.toList());
		
		return children;
	}

}
